<!--
 * @Description: 长来注册页面
 * @Author: Kerwin
 * @Date: 2024-08-28 17:36:15
 * @LastEditTime: 2025-11-25 13:48:16
 * @LastEditors:  Please set LastEditors
-->
<template>
  <view class="container">
    <!-- <u-navbar back-text="" title="注册" v-if="!isWeChatOfficial" :title-bold="false" color="#000"></u-navbar> -->
    <!-- <view v-if="isNeedBindPhone"> -->
    <view>
      <view style="position: relative; z-index: 2; background-color: #fff">
        <view class="logoBox">
          <view class="left">
            <view class="title">玺欢花·聚好赚</view>
          </view>
          <view class="right" @click="goHome">返回用户登录</view>
        </view>
        <view style="color: #FF6C18; margin: 20rpx 0rpx"
          ><text class="textColor" @click="toDownload"
            >下载APP享优惠 !</text
          ></view
        >
        <!-- 没有手机号的注册 -->
        <view v-if="!isOldUser">
          <u-form :model="form" ref="formRef" :rules="rules">
            <u-form-item label="手机号" prop="phone" label-width="120">
              <u-input
                v-model="form.phone"
                type="number"
                :maxlength="11"
                placeholder="请输入手机号"
                @blur="validatePhone"
              />
            </u-form-item>
            <view
              v-if="phoneError"
              style="color: red; font-size: 24rpx; text-align: left"
            >
              {{ phoneError }}</view
            >
            <view
              v-if="shouldShowMergeTip"
              style="color: #42b983; font-size: 24rpx; text-align: left"
            >
              检测到手机号：{{ form.phone }}已绑定账号：{{
                username
              }}，系统会将原账号和当前账号合并，以原账号为主</view
            >
            <u-form-item label="验证码" prop="code" label-width="120">
              <u-input
                v-model="form.code"
                type="number"
                :maxlength="6"
                placeholder="请输入验证码"
              />
              <u-verification-code
                :seconds="seconds"
                ref="uCode"
                @change="codeChange"
              ></u-verification-code>
              <u-button
                @tap="getCode"
                size="mini"
                type="success"
                ripple
                style="color: #fff; background-color: #FF6C18"
                >{{ tips }}</u-button
              >
            </u-form-item>
            <!-- <u-form-item label="密码" prop="password" label-width="120">
              <u-input
                v-model="form.password"
                :maxlength="18"
                placeholder="请设置密码"
              />
            </u-form-item> -->
            <u-form-item label="邀请码" prop="inviteCode" label-width="120">
              <u-input
                v-model="form.inviteCode"
                :maxlength="6"
                :disabled="disabled"
                placeholder="请输入邀请码"
              />
            </u-form-item>
          </u-form>
          <u-button
            v-if="phoneStatus == 1"
            :disabled="
              form.phone == '' || form.code == '' || form.inviteCode == ''
            "
            type="primary"
            @click="handleRegister"
            class="btn"
            >绑定手机号</u-button
          >
          <u-button
            v-if="phoneStatus == 2"
            :disabled="form.code === '' || phoneErrorStatus"
            type="primary"
            @click="show = true"
            class="btn"
            >合并手机号</u-button
          >
          <view class="user-agreement">
            进行注册意味着您同意
            <a
              href="https://www.blacksilverscore.com/download/user_agreement_license.html"
              >《用户协议》</a
            >
          </view>
        </view>
        <!-- 有手机号提示 -->
        <view v-else style="color: #42b983; font-size: 32rpx; text-align: left">
          当前微信号{{ form.uName }}和手机号:{{ form.phone }}已经注册成功!
        </view>
      </view>
      <image src="../../static/xihuanhua.png" mode="widthFix" class="footerbg" />
    </view>
    <!-- 授权弹窗 -->
    <u-popup
      v-model="showAuth"
      mode="bottom"
      :show-close="false"
      :mask-close-able="false"
      border-radius="20"
    >
      <view class="authBox">
        <view class="tit">
          <u-avatar :src="hy_logo" size="46"></u-avatar>
          <view class="label">黑银App 申请</view>
        </view>
        <view class="desc">
          <view class="desc-tit"> 获取您的微信昵称、头像 </view>
          <view class="desc-txt"> 提供具有辨识度的用户中心界面 </view>
        </view>
        <view class="content">
          <u-button
            type="success"
            class="hy-btn wx"
            open-type="getPhoneNumber"
            ripple
            @click="handleWxWebLogin"
          >
            <text class="iconfont hy-icon-wechat"></text>
            点击授权
          </u-button>
        </view>
      </view>
    </u-popup>
    <!-- 确认弹窗 -->
    <u-modal
      v-model="show"
      title="温馨提示"
      show-cancel-button
      @confirm="onsubmit"
      :content="content"
    >
    </u-modal>
  </view>
</template>
<script setup lang="ts">
import { reactive, ref, computed, nextTick, watch } from 'vue'
import { onLoad, onReady } from '@dcloudio/uni-app'
import { Md5 } from 'ts-md5'
import { useUserStore } from '@/store'
import { baseApi, userApi, enumAll } from '@/api'
import { getQueryVariable, isWeChat, route, getCookie } from '@/utils/common'
import { hy_logo } from '@/common/config'
import c_innovateBox from './c_innovateBox.vue'
import { useConfigStore } from '@/store'
import { innovate_type, innovate_shopId } from '@/api/enum'
import hyDownloadTips from '@/components/hy-download-tips/index.vue'
const userStore = useUserStore()
const isWeChatOfficial = ref(true)
const configStore = useConfigStore()
// #ifdef MP-WEIXIN
isWeChatOfficial.value = false
// #endif
const form = reactive<any>({
  password: '',
  code: '',
  phone: '',
  inviteCode: '',
  uName: ''
})
const uCode = ref()
const tips = ref('获取验证码')
const seconds = ref(60)
const formRef = ref()
const rules = {
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^(?:\d+|[a-zA-Z]+|[!@#$%^&*]+){6,18}$/,
      message: '密码由6-18位数字、英文或特殊字符组成!',
      trigger: 'blur'
    }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '验证码长度为6位', trigger: 'blur' }
  ],
  inviteCode: [
    { required: true, message: '请输入邀请码', trigger: 'blur' },
    { min: 6, max: 6, message: '邀请码长度为6位', trigger: 'blur' }
  ]
}
const withShareCode = ref(false)
const disabled = computed(() => {
  return withShareCode.value
})
const innovateRef = ref()
const innovateType = ref()
const shopId = ref()
const showAuth = ref(false)
const userPhone = ref<any>(null)
// 是否授权登录成功
const login_success = ref<any>(false)
// 是否是老用户
const isOldUser = ref(false)
// 是否需要绑定手机号
const isNeedBindPhone = ref(false)
const phoneError = ref('')
const phoneErrorStatus = ref(true)
const phoneStatus = ref(1) //1绑定手机号，2将账号合并
const username = ref('') //1绑定手机号，2将账号合并
const content = ref('是否确认绑定该手机号')
const show = ref(false)
const hebingUserId = ref('')
//小提示
const shouldShowMergeTip = computed(() => {
  return phoneStatus.value === 2 && !phoneErrorStatus.value
})

// 校验电话号码的方法
const validatePhone = async () => {
  const phoneRegex = /^1[3-9]\d{9}$/ // 中国大陆手机号正则表达式

  if (!form.phone) {
    phoneError.value = '联系电话不能为空'
    phoneErrorStatus.value = true
  } else if (!phoneRegex.test(form.phone)) {
    phoneError.value = '请输入有效的手机号码'
    phoneErrorStatus.value = true
  } else {
    phoneError.value = '' // 清除错误信息
    phoneErrorStatus.value = false
    const { data } = await userApi.userList({
      phone: form.phone
    })
    if (data.records && data.records.length > 0) {
      uni.showToast({
        title: '该手机号已绑定账号,继续操作将合并账号',
        icon: 'none',
        duration: 3000
      })
      phoneStatus.value = 2
      username.value = data.records[0].nickname
      content.value = '是否确认合并该手机号'
      hebingUserId.value = data.records[0].id
    } else {
      content.value = '是否确认绑定该手机号'
      phoneStatus.value = 1
    }
  }
}
function codeChange(text: string) {
  tips.value = text
}
async function getCode() {
  if (!form.phone) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none'
    })
    return
  }
  if (uCode.value.canGetCode) {
    try {
      //BindPhoneCode  重新绑定手机号  5
      const { data } = await baseApi.smsSend({
        type: enumAll.sms_enum_type.BindPhoneCode,
        phone: form.phone
      })
      uCode.value.start()
    } catch {}
  }
}
// 合并手机号
const onsubmit = async () => {
  if (!hebingUserId.value)
    return uni.showToast({
      title: '用户id错误,请刷新重试',
      icon: 'none'
    })
  bindRelation(hebingUserId.value)
  if (!phoneErrorStatus.value) {
    const { msg, data } = await userApi.UserBindPhoneAndMerge({
      phone: form.phone.toString(),
      code: form.code.toString(),
      status: 2
    })
    if (msg === '操作成功') {
      uni.showToast({
        title: msg,
        icon: 'success'
      })
      setTimeout(async () => {
        // 清除之前手机号的token缓存
        uni.removeStorageSync('accessToken')
        uni.navigateTo({
          url: `/pages/register/success?mode=11`
        })
      }, 1000)
    } else {
      uni.showToast({
        title: '绑定失败',
        icon: 'error'
      })
    }
  } else {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    })
  }
}
// 绑定手机号
const handleRegister = async () => {
  const { msg, data } = await userApi.UserBindPhoneAndMerge({
    phone: form.phone.toString(),
    code: form.code.toString(),
    status: 1,
    mode: 11
  })
  if (msg === '操作成功') {
    uni.showToast({
      title: msg,
      icon: 'success'
    })
    uni.navigateTo({
      url: `/pages/register/success?mode=11`
    })
  } else {
    uni.showToast({
      title: msg || '绑定失败，请联系客服',
      icon: 'error'
    })
  }
}

// 更新用户信息的模式为6
async function updateUserInfo() {
  //  uni.setStorageSync('hyType)是h5页面获取模式
  uni.setStorageSync('hyType', JSON.stringify({ name: '玺欢花', id: 11 }))
  uni.showLoading({
    title: '用户信息更新中'
  })
  await userApi
    .userInfoUpdate({
      nickname:
        userStore.wxUserInfoGetter?.nickname ||
        form.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') ||
        '',
      avatar: userStore.wxUserInfoGetter?.headimgurl || '',
      // userInfoUpdate是app获取模式
      // id: loginUserId.vlue,
      mode: 11
    })
    .finally(() => {
      uni.hideLoading()
    })
}
//授权登录按钮
async function handleWxWebLogin() {
  const { code } = await userStore.wxAuth()
}
//绑定关系
async function bindRelation(userId: any) {
  if (innovateType.value == 0 && !shopId.value) {
    uni.showToast({
      title: '店铺id 未正确设置',
      icon: 'none',
      duration: 3000
    })
    return
  }

  try {
    const res = await userApi.innovateBind({
      userId,
      shareCode: form.inviteCode,
      innovateType: innovateType.value == 0 ? 3 : innovateType.value,
      shopId:
        innovateType.value == 0 && shopId.value
          ? shopId.value
          : innovate_shopId[innovateType.value as keyof typeof innovate_shopId]
      // shopId: innovate_shopId[innovateType.value  as keyof typeof innovate_shopId]
    })

    uni.removeStorageSync('innovateType')

    if (res.code == 200) {
      uni.showToast({
        title: '绑定成功',
        icon: 'none',
        duration: 6000
      })
    }
  } catch (error: any) {
    // 检查错误码是否为 500
    if (error?.code != 500) {
      // 其他错误处理
      uni.showToast({
        title: '绑定失败，请联系客服',
        icon: 'none',
        duration: 3000
      })
    } else {
      // 500 错误处理
      uni.showToast({
        title: error.msg,
        icon: 'none',
        duration: 6000
      })
    }
  }
}
//返回用户登录
function goHome() {
  route({
    url: '/pages/login/index'
  })
}
//下载app
function toDownload() {
  window.open(`https://www.blacksilverscore.com/download/downloadXhh.html?mode=11`)
}
//初始化数据
onLoad(async (option) => {
  withShareCode.value = !!option?.shareCode
  if (option?.innovateType) {
    innovateType.value = option?.innovateType
    shopId.value = option?.shopId
  }

  // #ifdef H5
  isWeChatOfficial.value = isWeChat()
  // #endif
  const shopCode = uni.getStorageSync('shopCode')
  const shareCode = option?.shareCode || uni.getStorageSync('shareCode')
  const shopOwnerShareCode = uni.getStorageSync('shopOwnerShareCode')
  if (shareCode) {
    form.inviteCode = shareCode
  } else if (shopOwnerShareCode) {
    form.inviteCode = shopOwnerShareCode
  } else if (shopCode) {
    form.shopCode = shopCode
  }
  console.log('form==>', form)
  if (isWeChatOfficial.value) {
    const code = getQueryVariable('code')
    // 待还原的代码
    // showAuth.value = !code

    if (code) {
      await userStore.wxWebLogin(code)
      const login_success = await userStore.hlhyLoginByOpenId()
      if (login_success) {
        //微信授权成功
        // 登录成功后检查手机号
        setTimeout(async () => {
          const userId = userStore.userInfo.id
          await bindRelation(userId)
          updateUserInfo()
          // 绑定关系
          if (userStore.userInfo.phone) {
            form.phone = userStore.userInfo.phone
            form.uName = userStore.userInfo.nickname
            isOldUser.value = true
            // 已绑定手机
            uni.showToast({
              title: '登录成功',
              icon: 'success'
            })
            setTimeout(async () => {
              uni.navigateTo({
                url: `/pages/register/success?mode=11`
              })
            }, 1000)
          }
        }, 1000)
      }
    }
  }
})
onReady(() => {
  // formRef.value.setRules(rules)
})
</script>

<style lang="scss" scoped>
.page {
  max-width: 750rpx;
  margin: 0 auto;
}

.container {
  background: #fff;
  overflow: hidden;
  min-height: 100vh;
  padding: 30rpx;
  position: relative;

  .logoBox {
    display: flex;
    justify-content: space-between;
    text-align: left;
    align-items: center;

    .left {
      font-size: 40rpx;
      font-weight: 500;
      color: #FF6C18;
      .logo {
        width: 168rpx;
        height: 44rpx;
        margin: 0 auto;
        margin-top: 30rpx;
        border-radius: 10rpx;
      }

      .title {
        font-size: 40rpx;
        font-weight: 500;
        color: #FF6C18;
        font-weight: bold;
      }
    }
    .right {
      font-size: 24rpx;
      color: #FF6C18;
    }
  }

  .btn {
    color: #ffffff;
    text-align: center;
    justify-content: center;
    width: 632rpx;
    height: 84rpx;
    background: #FF6C18 !important;
    margin-top: 80rpx !important;
    font-size: 32rpx;
    border-radius: 42rpx;
  }

  .user-agreement {
    font-size: 24rpx;
    font-weight: 400;
    color: #666666;
    margin-top: 40rpx;
    text-align: center;

    a {
      color: rgba(42, 142, 205, 1) !important;
      border: none;
      text-decoration: none;
    }
  }

  .footerbg {
    position: absolute;
    display: block;
    width: 654rpx;
    height: 324rpx;
    z-index: 1;
    left: 50%;
    bottom: 30rpx;
    transform: translate(-50%,0);
  }
}

.authBox {
  padding: 30rpx;

  .tit {
    font-size: 28rpx;
    display: flex;
    align-items: center;
    justify-content: flex-start;

    .label {
      margin-left: 10rpx;
    }
  }

  .desc {
    &-tit {
      font-size: 28rpx;
      color: #333333;
      margin-top: 30rpx;
      font-weight: bold;
    }

    &-txt {
      font-size: 24rpx;
      color: #666666;
      margin-top: 10rpx;
    }
  }

  .content {
    padding: 30rpx 0;

    .hy-icon-wechat {
      color: #fff;
      margin-right: 15rpx;
      font-size: 36rpx;
    }
  }
}
</style>
